package com.liuyi.usercenterservice.tools;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.lang.reflect.Field;

/**
 * @author 刘燚
 * @version v1.0.0
 * @Description TODO
 * @createDate：2024/4/21 22:08
 * @email liuyia2022@163.com
 */
public class SetQueryUtils {
    /**
     * 通过反射获取公有属性值给query设置查询条件
     *
     * @param classData
     * @param <T>
     * @return
     * @throws IllegalAccessException
     */
    public static <T> QueryWrapper setEq(T classData) throws IllegalAccessException {
        if (classData == null) {
            return new QueryWrapper<>();
        }
        QueryWrapper<T> queryWrapper = new QueryWrapper();
        Class<?> aClass = classData.getClass();
        Field[] fields = aClass.getFields();
        for (Field field : fields) {
            String value = "String".equals(field.getType().getName()) ? (String) field.get(classData) : String.valueOf(field.get(classData));
            if (value != null) {
                queryWrapper.like(field.getName(), "%" + value + "%");
            }
        }
        return queryWrapper;
    }

    public static <T> QueryWrapper setLike(T classData) throws IllegalAccessException {
        if (classData == null) {
            return new QueryWrapper<>();
        }
        QueryWrapper<T> queryWrapper = new QueryWrapper();
        Class<?> aClass = classData.getClass();
        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.getName().equals("serialVersionUID") || field.get(classData) == null) {
                continue;
            }
            String value = field.getType().getName().equals("java.lang.String") ? (String) field.get(classData) : String.valueOf(field.get(classData));
            if (value != null) {
                queryWrapper.like(StringUtils.toDatabaseField(field.getName()), "%" + value + "%");
            }
        }
        return queryWrapper;
    }
}
